package com.moana.buyTicket.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.datastore.DataStoreCache;

import com.moana.buyTicket.entity.Ticket;
import com.moana.buyTicket.entity.TranFlow;

public class DBOperator {
	
	private static PersistenceManagerFactory pmf = null;
	
	private volatile static List<Ticket> tickets ;  
	
	//读取电影票
	public static List<Ticket> readTickets() {
	if(tickets==null){
		synchronized (DBOperator.class) {
			if(tickets==null){
				tickets = new ArrayList<Ticket>();
				pmf = JDOHelper.getPersistenceManagerFactory("buyTicket");
				PersistenceManager pm = pmf.getPersistenceManager();
				Transaction tx = pm.currentTransaction();
				try{
					tx.begin();
					Ticket ticket = new Ticket();
					ticket.setStatus(0);
					Query query = pm.newQuery(ticket);
					Collection queryResult = (Collection) query.execute();
					List<Ticket> tickets = (List<Ticket>) pm.detachCopyAll(queryResult);
					tx.commit();
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					if(tx.isActive())
					{
						tx.rollback();
					}
					pm.close();
					pmf.close();
				}
			}
		}
	}
		return tickets;
	}
	
	//更新电影票
	public static String updateTickets(List<Ticket> tickets,List<TranFlow> tranFlows){
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try{
			tx.begin();
			//交易流水表插入
			for(TranFlow tranFlow:tranFlows){
				pm.makePersistent(tranFlow);
			}		
			//******电影票状态更新******
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(tx.isActive()){
				tx.rollback();
			}
			pm.close();
			pmf.close();
		}
		
		return "0";
	}
	
	
}
